<template>
  <div class="app-container customer-div">
    <div>
      <el-radio-group v-model="listQuery.tab" size="small" @change="changeTab">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="20">待采购经理审核</el-radio-button>
        <el-radio-button label="30">待财务审核</el-radio-button>
        <el-radio-button label="40">待付款</el-radio-button>
      </el-radio-group>
    </div>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
        <el-form-item label="收款方：">
          <el-input v-model="listQuery.receiveCompany" clearable></el-input>
        </el-form-item>
        <el-form-item label="申请日期：">
          <el-date-picker
            v-model="listQuery.applyTime"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="状态：" v-if="listQuery.tab == 'all'">
          <el-select v-model="listQuery.applyState" filterable placeholder="请选择" clearable style="width:200px" >
            <el-option :key="0" label="待采购员审核" :value="0"></el-option>
            <el-option :key="20" label="待采购部门负责人确认" :value="20"></el-option>
            <el-option :key="30" label="待财务负责人审核" :value="30"></el-option>
            <el-option :key="40" label="待支付" :value="40"></el-option>
            <el-option :key="50" label="已支付" :value="50"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
            :loading="btnloading5"
            @click="downloadExcel('add')"
            type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table v-loading="listLoading" :data="tableData" border style="width: 100%; margin-top: 20px">

        <el-table-column  label="付款申请编号"  align="center" prop="orderSn" min-width="150">
          <template slot-scope="scope">
                {{scope.row.applySn}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="申请日期" min-width="100">
          <template slot-scope="scope">
            {{scope.row.applyDate}}
          </template>
        </el-table-column>
        <el-table-column
          label="收款方"
          align="center" min-width="150">
          <template slot-scope="scope">
            {{scope.row.receiveCompany}}
          </template>
        </el-table-column>
        <el-table-column
          min-width="100"
          label="付款方"
          align="center">
          <template slot-scope="scope">
            {{scope.row.fromCompany}}
          </template>
        </el-table-column>
        <el-table-column
          min-width="100"
          prop="billNum"
          label="单据数"
          align="center">
        </el-table-column>
        <el-table-column
          align="center"
          min-width="100"
          label="付款方式">
          <template  slot-scope="scope">
            {{scope.row.applyPaymentCode | fifPaymentCode}}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="150"
          label="合计付款金额">
          <template  slot-scope="scope">
            {{scope.row.applyPayAmount}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="150"
          label="实际付款金额">
          <template  slot-scope="scope">
            {{scope.row.actualPayAmount}}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="left"
          min-width="150"
          label="附件">
          <template  slot-scope="scope">
              <img :src="item" v-for="item in scope.row.applyPayContract"  style="width:50px;height:50px;object-fit: contain;margin-right:5px;margin-bottom:5px;"/>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          header-align="center"
          min-width="150"
          label="付款备注">
          <template  slot-scope="scope">
            {{scope.row.applyPayRemark}}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="申请人">
          <template  slot-scope="scope">
            {{scope.row.applyUserName}}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="150"
          label="申请时间">
          <template  slot-scope="scope">
            {{scope.row.applyTime}}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="付款人">
          <template  slot-scope="scope">
            {{scope.row.payUserName}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="150"
          label="付款时间">
          <template  slot-scope="scope">
            {{scope.row.payTime}}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="left"
          min-width="150"
          label="付款凭证">
          <template  slot-scope="scope">
            <img :src="scope.row.payContent" style="width:80px;height:80px;object-fit: contain" v-if="scope.row.payContent != ''"/>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="状态">
          <template  slot-scope="scope">
            {{scope.row.payState | fifpayState}}
          </template>
        </el-table-column>


        <el-table-column
          fixed="right"
          width="100"
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.payState == 40"
              type="text"
              size="mini"
              @click="showDialog(scope.row)">付款
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="toInfo(scope.row)">查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

    <!--付款-->
    <el-dialog
      :close-on-click-modal="false"
      title="付款"
      :visible.sync="dialogVisible"
      width="600px">
      <el-form :model="payForm" size="mini" label-width="100px" ref="payForm" :rules="rules">
        <el-form-item label="收款方：" >
          {{ payForm.agentProcessor }}
        </el-form-item>
        <el-form-item label="收款金额：">
          {{ payForm.actualPayAmount }}
        </el-form-item>
        <el-form-item label="付款日期：" >
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="payForm.payTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="付款凭证：" prop="payContent">
          <div style="width: 100%;height: 150px; border:1px solid #DCDFE6;cursor: default;border-radius: 4px;">
            <img id="imgNode" :src="payForm.payContent" style="width:100%;height:100%;object-fit: contain;border:0" v-show="payForm.payContent != ''">
            <el-input type="hidden" v-model="payForm.payContent"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="付款备注：" >
          <el-input type="textarea" :rows="2" v-model="payForm.payRemark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm4" :loading="btnLoading4">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {warehouseList,warehouseAdd,warehouseEdit,delWarehouse,} from '@/api/company'
import {agentProcessApplyPay,getOrderUsersList,uploadBase64,getQiniuToken,agentProcessApplyList} from '@/api/partner'
import {validateCommission} from '@/utils/validate';
import {formatDate} from '@/utils/date';
import store from '@/store'
import warehouseInfo from './warehouseInfo.vue'
import { mapGetters } from 'vuex'
import scheduling from "./scheduling";
import limit from "./limit";
const defaultListQuery={
  tab:'all',
  "applyState" : '',  //申请状态(0待采购员审核,10作废,20-待采购部门负责人确认,30-待财务负责人审核, 待支付:40,已支付:50)
  "receiveCompany" : "", //收款方
  "applyTime" : [],  //申请时间
  "pageNum" : 1,
  "pageSize" : 10
};

const defaultPayForm={
  "applyId" : '',  //付款申请单ID
  "payContent" : "", //付款凭证
  "payRemark" : "", //付款备注
  "payTime" : "", //支付日期
  "actualPayAmount":'',
  "agentProcessor":'',
};

export default {
  name: "index",
  data(){
    const validatePayAmount = (rule, value, callback) => {
      if (!validateCommission(parseFloat(value))) {
        callback(new Error('非负整数或小数'))
      } else if(value > this.priceForm.unPaidAmount){
        callback(new Error('收款金额大于未付金额'))
      }else {
        callback()
      }
    };
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      count: 0,
      listLoading: false,
      userOptionList:[],
      roles:store.getters.roles ? store.getters.roles : [],
      btnLoading:false,
      payForm:JSON.parse(JSON.stringify(defaultPayForm)),
      dialogVisible:false,
      upUrl:'',
      uploadToken:{
        token:'',
      },
      imgDomain:'',
      btnLoading4:false,
      rules:{
        payContent:[{required: true, trigger: 'change',message: '此项必填',}],
      },
      btnloading5:false,
    }
  },
  components : {
    warehouseInfo:warehouseInfo
  },
  computed: {

  },
  created() {
    this.getUserOptionList();
    this.getList();
    this.pasteImage();
  },
  filters: {
    fifpayState(val){
      if(val == 0){
        return '待采购员审核'
      }else if(val == 10){
        return '作废'
      }else if(val == 20){
        return '待采购部门负责人确认'
      }else if(val == 30){
        return '待财务负责人审核'
      }else if(val == 40){
        return '待支付'
      }else if(val == 50){
        return '已支付'
      }
    },
    fifPaymentCode(val){
      if(val == 'cash'){
        return '现金汇款'
      }else if(val == 'chengdui'){
        return '承兑'
      }
    },
  },
  watch:{
    upUrl(){
      let data = {};
      let pic = this.upUrl.replace(/^.*?base64,/, '');
      data.pic = pic;
      data.token = this.uploadToken.token;
      data.imgDomain = this.imgDomain;
      uploadBase64(data).then((res)=>{
        if(res.src){
          this.payForm.payContent = res.src;
        }else{
          this.$message.error('上传失败')
        }
      });
    },
  },
  methods:{
    toInfo(item){
      let routeData = this.$router.resolve({name:'purchasePayOEMInfo',query:{id:item.applyId}});
      window.open(routeData.href);
    },
    //下载excle
    downloadExcel(){
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      this.btnloading5 = true;
      agentProcessApplyList(params).then((res)=>{
        this.btnloading5 = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnloading5 = false;
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    changeTab(val){
      if(val == 'all'){
        this.listQuery.applyState = ''
      }else{
        this.listQuery.applyState = val
      }
      this.handleSearchList()
    },

    //获取七牛TOKEN
    getUploadToken(){
      return getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },

    //粘贴图片
    pasteImage() {
      let upUrl = ''
      document.addEventListener('paste',(event)=> {
        let isChrome = false;
        if (event.clipboardData || event.originalEvent) {
          //某些chrome版本使用的是event.originalEvent
          let clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
          if(clipboardData.items){
            // for chrome
            let  items = clipboardData.items, len = items.length, blob = null;
            isChrome = true;
            for (let i = 0; i < len; i++) {
              if (items[i].type.indexOf("image") !== -1) {
                //getAsFile() 此方法只是living standard firefox ie11 并不支持
                blob = items[i].getAsFile();
              }
            }
            if(blob!==null){
              let blobUrl=URL.createObjectURL(blob);
              // this.priceForm.blobImg = blobUrl;
              // document.getElementById("imgNode").src=blobUrl;
              let reader = new FileReader();
              // base64码显示

              reader.onload =  (event)=> {
                // event.target.result 即为图片的Base64编码字符串
                // this.priceForm.payContent = event.target.result;
                // document.getElementById("imgNode").src=base64_str;
                this.upUrl = event.target.result;
              };
              reader.readAsDataURL(blob);
            }
          }
        }
      });
    },

    handleConfirm4(){
      this.$refs.payForm.validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.payForm))
          this.btnLoading4 = true;
          agentProcessApplyPay(data).then(()=>{
            this.btnLoading4 = false;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.dialogVisible = false;
            this.getList()
          }).catch(()=>{
            this.getList()
          })

        }
      })
    },

    //显示付款弹窗
    showDialog(item){
      this.dialogVisible = true;
      this.payForm = JSON.parse(JSON.stringify(defaultPayForm))
      this.payForm.applyId = item.applyId;
      this.payForm.agentProcessor = item.agentProcessor;
      this.payForm.actualPayAmount = item.actualPayAmount;

      this.getUploadToken();

    },


    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList().then((res)=>{
        this.userOptionList = res;
      })
    },


    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      agentProcessApplyList(this.listQuery).then(response => {
        this.tableData = response.list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },

    //去收款单页
    toReceiptList(item){
      localStorage.setItem('accountingListQuery', JSON.stringify(this.listQuery));
      this.$router.push({name:'receiptList',query:{orderSn:item.orderSn}})
    },
  },
}
</script>

<style scoped lang="scss">
.avatar-uploader{
  margin-bottom:10px;
  display: inline-block;
  width:80px;
  height:80px;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 80px;
  vertical-align: middle;
}
</style>
